package com.ddw.weewar.api;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Utilities class for helping with http methods
 */
public abstract class HttpUtils {

    /**
     * Makes a http GET request and returns the response as text
     * @param url the url to request
     * @return the response from the url
     * @throws RuntimeException if there is a problem making the request
     */
    public static String get(String url) throws RuntimeException {
        // Create the url
        URL url_;
        try {
            url_ = new URL(url);
        } catch(MalformedURLException e) {
            throw new RuntimeException("Failed to create URL", e);
        }

        // Create the connection
        HttpURLConnection connection;
        try {
            connection = (HttpURLConnection) url_.openConnection();
        } catch (IOException e) {
            throw new RuntimeException("Failed to create connection", e);
        }

        // Read the response
        StringBuffer result;
        try {
            InputStream in = new BufferedInputStream(connection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch(IOException e) {
            throw new RuntimeException("Failed to read the response", e);
        } finally {
            connection.disconnect();
        }

        return result.toString();
    }

}
